<template>
    <div>
      <!-- 搜索栏 ： 两个搜索框  搜索按钮  添加部门按钮  批量删除   -->
      <el-row>
        <el-col :span="1"></el-col>
        <el-col :span="4">
             <el-input placeholder="请输入真实姓名搜索" v-model="query.realname"/>
        </el-col>
        <el-col :span="2">
                <el-button type="primary" plain @click="getByPage">搜索</el-button>
        </el-col>
        <el-col :span="3">
                <el-button type="success" plain @click="showDialog">新增员工</el-button>
        </el-col>
        <el-col :span="3">
                <el-button type="danger" plain @click="handleBatchDel">批量删除</el-button>
        </el-col>
        
      </el-row>
      <!-- 表格 -->
      <el-row>
        <el-col :span="1"></el-col>
        <el-col :span="20">
            
          <el-table :data="pb.records" 
                    stripe 
                    border
                    @selection-change="handleSelectionChange">
            <el-table-column type="selection"  width="55" />
            <el-table-column type="index" width="50" />
            <el-table-column prop="realname" label="真实姓名" width="120px"/>
            <el-table-column prop="department.deptName" label="部门" width="120px"/>
            <el-table-column prop="registLevel.registName" label="挂号级别" width="120px"/>
            <el-table-column prop="role.name" label="角色" width="120px"/>
            <el-table-column label="状态" width="180px">
              <template #default="scope">
                  <el-switch
                      v-model="scope.row.delmark"
                      size="small"
                      active-text="未删除"
                      inactive-text="已删除"
                      :active-value="1"
                      :inactive-value="0"
                      @change="changeDelmark(scope.row)"
                  />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250px">
                  <template #default="scope">
                    
                    <el-button size="small" @click="resetPassword(scope.row.id)">
                      重置密码
                    </el-button>
                    <el-button size="small" @click="handleEdit(scope.row.id)">
                      编辑
                    </el-button>
                    <el-button
                      size="small"
                      type="danger"
                      @click="handleDelete(scope.row.id)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
          </el-table>
            
        </el-col>
        
      </el-row>  
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="6"></el-col>
        <el-col :span="12">
             <el-pagination
                  v-model:current-page="query.current"
                  v-model:page-size="query.size"
                  :page-sizes="[5, 8, 10, 20]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pb.total"
                  @size-change="getByPage"
                  @current-change="getByPage"
                />
        </el-col>
        
      </el-row>  
      
      <!-- 编辑部门信息的对话框  用于添加和修改 -->
      <el-dialog v-model="dialogFormVisible" title="编辑部门信息" width="500" draggable>
          <el-form :model="form">
            <el-form-item label="真实姓名" :label-width="formLabelWidth">
              <el-input v-model.trim="form.realname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="部门" :label-width="formLabelWidth">
                <el-input v-model.trim="form.department.deptName" autocomplete="off" />
            </el-form-item>
            <!-- 这里写一个下拉列表 -->
            <el-form-item label="挂号级别" :label-width="formLabelWidth">
            <!-- 用作挂号级别的选择框 -->
            <!-- 这里由于没有加上id的值所以在新添加的时候，并没有显示出来 -->
             <!-- 最好的办法就是在编辑的时候页面上显示的一个，文字但是在vue中绑定的是一个id -->
                  <el-select v-model="form.registLevel.registName" placeholder="请选择挂号级别">
                      <el-option
                        v-for="item in optionsRegistName"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label"
                     />
                  </el-select>
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth">
              <el-select v-model="form.role.name" placeholder="请选择角色">
                      <el-option
                        v-for="item in optionsRole"
                        :key="item.value"
                        :label="item.label"
                        :value="item.label">
                      </el-option>
                  </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="addOrUpdate">
                确认提交
              </el-button>
            </div>
          </template>
    </el-dialog>
      
    </div>
  </template>
  
  <script setup>
  //引入http请求的通用方法
  import httpRequest from '../../common/index.js';
  import { onMounted, ref, getCurrentInstance } from 'vue';
  import { ElMain, ElMessage,ElMessageBox } from 'element-plus';
  import { nanoid } from 'nanoid';
  import { Plus } from '@element-plus/icons-vue'
  
    const optionsRegistName=ref([
      {
        value:1,
        label:'专家号',
      },
      {
        value:2,
        label:'普通号',
      },
      {
        value:3,
        label:'主任医生号'
      }
    ])
    const optionsRole=ref([
    {
      value:1,
      label:'超级管理员',
      },
      {
        value:2,
        label:'挂号收费员',
      },
      {
        value:3,
        label:'门诊医生'
      },
      {
        value:4,
        label:'检查医生',
      },
      {
        value:5,
        label:'检验医生',
      },
      {
        value:6,
        label:'药房管理员'
      },
      {
        value:7,
        label:'处置医生'
      }
    ])
    let {proxy} = getCurrentInstance();
  
    let baseUrl = proxy.$baseUrl;
  
    //对话框是否显示
    let dialogFormVisible = ref(false);
    let formLabelWidth = ref('100px');
    
    //表单数据 添加和修改
    let form = ref({
        realname:'',
        //部门名称
        department:{
          deptName:''
        },
        registLevel:{
          registName:''
        },
        role:{
          name:''
        }
    })
    //点新增部门信息按钮弹出对话框
    const showDialog = ()=>{
        
        dialogFormVisible.value = true;
        //数据清除
        form.value = {
          realname:'',
          department:{
            deptName:''
          },
          registLevel:{
            registName:''
          },
          role:{
            name:''
          }
        };
    }
  
    //分页+搜索条件
    let query = ref({
        current: 1,
        size: 5,
        realname:''
    })
    
    //分页对象 total  pages  data(集合)
    let pb = ref({
        total: 0,
        pages: 0,
        records: []
    })
  
    //分页查询部门信息
    const getByPage = ()=>{
  
      httpRequest(
              proxy,
              'post',
              '/employee/page',
              query.value,
              (resultBean)=>{
                  pb.value = resultBean.data;
              })
    }
    
    //添加或修改
    const addOrUpdate = ()=>{
        proxy.$axios({
            method: 'post',
            url: '/employee/save',
            data: form.value
        }).then(res=>{
            let resultBean = res.data;
            if(resultBean.code == 200){
                getByPage();
                dialogFormVisible.value = false;
                ElMessage.success('保存部门信息成功');
            }else{
                ElMessage.error(resultBean.msg);
            }
        })
    }
    
    //处理数据回显
    //查询这个这个员工在部门表是什么部门以及挂号的级别
    const handleEdit = (EmployeeId)=>{
        console.log('回显：EmployeeId----',EmployeeId);
        //根据id查询对应的实体数据
        proxy.$axios({
            method: 'get',
            url: '/employee/getEmp/'+EmployeeId
        }).then(res=>{
            let resultBean = res.data;
            if(resultBean.code == 200){
                form.value = resultBean.data;
                dialogFormVisible.value = true;
            }else{
                ElMessage.error(resultBean.msg);
            }
        })
    }
    
    //处理删除
    const handleDelete = (EmployeeId)=>{
        console.log('删除：EmployeeId----',EmployeeId);
        ElMessageBox.confirm(
            '您确定要删除该部门信息吗？',
            '删除提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
                
                //确定删除
                proxy.$axios({
                    method: 'delete',
                    url: '/employee/'+EmployeeId
                }).then(res=>{
                    let resultBean = res.data;
                    if(resultBean.code == 200){
                        ElMessage.success('删除成功');
                        getByPage();
                    }else{
                        ElMessage.error(resultBean.msg);
                    }
                })
                
            })
            .catch(() => {
                 ElMessage.info('取消删除');
            })
    }
    
    // const selectable = (row,index)=>{
       //  console.log('selectable',row,index);
       //  return true;
    // }
    
    //选中项的id集合
    let selectOptions = ref([]);
    
    //表格中多选框选中或取消时会触发  也就是选中项变化
    const handleSelectionChange = (newSelection)=>{
        console.log('选中项改变',newSelection);
        selectOptions.value = []; //清空
        newSelection.forEach((selOp)=>{
            console.log(selOp.id);
            selectOptions.value.push(selOp.id);
        });
    }
    
    //批量删除的函数
    const handleBatchDel = ()=>{
        console.log(selectOptions.value);
        if(selectOptions.value.length==0){
            ElMessage.info('请选中至少一条记录之后再进行删除');  
            return;
        }
        
        ElMessageBox.confirm(
            '您确定要删除选中的部门信息吗？',
            '删除提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
  
              console.log(selectOptions.value);
              console.log(typeof(selectOptions.value));
              console.log(JSON.stringify(selectOptions.value));
  
              let str = JSON.stringify(selectOptions.value);
              str = str.substring(1,str.length-1);
                      
                      //确定删除
                  proxy.$axios({
                      method: 'get',
                      url: '/employee/batch1/'+str,
                  }).then(res=>{
                      let resultBean = res.data;
                      if(resultBean.code == 200){
                          ElMessage.success('删除成功');  
                          getByPage();
                      }else{
                          ElMessage.error(resultBean.msg);
                      }
                  })
                    
                      
            })
            .catch(() => {
                 ElMessage.info('取消删除');
            })
    }
    
    //上传图片的回显链接
    let imageUrl = ref('');
    
    //上传成功之后的回调
    const handleAvatarSuccess = (response,uploadFile)=>{
        ElMessage.success('上传成功');
        console.log('上传成功，',response,uploadFile);
        //负责上传完成 图片回显
        imageUrl.value = response.data;
        //将上传成功的链接放入form表单， 添加或修改时会携带到服务端
        form.value.EmployeeImg = response.data;
    }
    
    //上传之前预检文件
    const beforeAvatarUpload = (rawFile)=>{
        //文件类型不符合要求 或者 文件大小超过要求  都不能上传
        if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
            ElMessage.error('Avatar picture must be JPG format!')
            return false
          } else if (rawFile.size / 1024 / 1024 > 5) {
            ElMessage.error('Avatar picture size can not exceed 5MB!')
            return false
          }
          //可以上传
          return true
    }
  
    //********************************* */
    const changeDelmark = (row)=>{
  
      httpRequest(
              proxy,
              'put',
              '/employee/change/delmark',
              {
                  id: row.id,
                  delmark: row.delmark
              },
              (resultBean)=>{
                  ElMessage.success("修改删除状态成功");
              })
    }
      const resetPassword=(id)=>{
        httpRequest(
          proxy,
          'put',
          '/employee/resetpass/'+id,
          null,
          resultBean=>{
            ElMessage.success("重置密码成功");
          }
        )
      }
    
    onMounted(()=>{
        getByPage();
    })
  
  
  </script>
  
  <style scoped>
      .avatar-uploader .avatar {
        width: 100px;
        height: 100px;
        display: block;
      }
  </style>
  
  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
  }
  </style>